// pages/templateAdd/templateAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,

    //xx选择框
    showXxx:false,
    //xxx选择数据
    xxxList:[{
      id:1,
      text:'选项1'
    },{
      id:2,
      text:'选项2'
    }],
    //搜索xxx
    valueSearchXxx:'',

    //上传的图片
    imgUrls:[],




    //开始时间选择框
    showStartTime:false,
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2:null,
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },


    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
    valueSearch: '',


      //循环表单列表
      loopList:[],



  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // Toast.fail({
    //   duration: 5000,
    //   message: 'xxx'
    // });

    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('xxx传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取修改数据
        this.getInfo();
      }
    }
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let loopList=td.loopList;
    let flag=false;

    console.log('obj');
    console.log(obj);

    console.log('editInfo');
    console.log(editInfo);

    console.log('loopList');
    console.log(loopList);

    let field1=obj.field1.trim();

    //非空验证
    if(!this.formNotEmpty(field1,'field1Message','请输入xxx')){
      return;
    }

    if(!editInfo.xxx){
      Toast.fail('请选择xxx');
      return;
    }

    //手机号格式
    let phone=obj.phone.trim();
    if(!util.checkPhoneFormat(phone)){
      this.setData({
        phoneMessage: '手机号格式错误',
        disabled: true
      })
      return;
    }

    //验证xxx是否存在
    flag=this.isExist(xxx).then(value => {
      if(!value){
        this.setData({
          xxxMessage: 'xxx',
          disabled: true
        })
      }
      return value;
    });


    //处理循环表单
    if(loopList.length){
        let len=loopList.length-1;
        if(loopList[len].name1){
        }else{
            Toast.fail('当前xx信息未完成');
            return;
        }
    }else{
        Toast.fail('请添加xx');
        return;
    }



    //权限
    let authArr=[editInfo.companyId, editInfo.fid];
    authArr=util.arrayRepeatEmpty(authArr);

    let param={
      className:'xxx',
      data:{
        requestToken: td.code,
        id: td.id,
        // xxx:td.xxx,
        // xxx: editInfo.xxx,
        // xxx: Boolean(editInfo.xxx),
        dataAuthority: {
          depart: authArr
        },
        appId: [app.globalData.myAppId]
      }
    }

    console.log(param.data);
    return;

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })


    //有Promise时
    Promise.all([flag]).then(value => {
      let passed=value.every(val=>{
        return val;
      });
      if(passed){
        let param={

        }

        //CommonService.goSave...
      }
    });
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleParts',
      data: {
        id:this.data.id,
        selectFields: ['id','xxx']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('xx信息回显');
        console.log(result);

        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //验证xxx是否存在/重复
  isExist(equipmentNo){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        equipmentNo:equipmentNo,
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        selectFields:["id"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //扫码
  onScanCode(e) {
    var _this = this;
    wx.scanCode({
      success: (res) => {
        let xxx='editInfo.xxx';
        _this.setData({
          [xxx]: res.result
        })
      }
    })
  },

  //显示xxx
  onShowxxx(){
    this.setData({
			showXxx: true
    })
    this.getXxxList();
  },

  //查询xxx
  getXxxList(){
    // this.setData({
    //   xxxList: []
    // })

    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        searchAll: true,
        type: 2,
        selectFields: ['id', 'name']
      }
    }

    //模糊查询
    if(this.data.valueSearchXxx){
      param.data.xxx='%' + this.data.valueSearchXxx + '%';
    }

    CommonService.goFindList(param).then(res=>{
      //console.log(res);

      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          xxxList: arr
        })
      }
    }).catch((error) => {
    })

    // CommonService.goFindList(param).then(res=>{
    //   console.log(res);
    //   if(res.data.data && res.data.data.result && res.data.data.result.length){
    //     let result=res.data.data.result;

    //   }
    // }).catch((error) => {
    // })

  },

  //隐藏xxx
  onCloseXxx(){
    this.setData({
      showXxx: false,
      valueSearchXxx:''
    })
  },

  //确认xxx
  onConfirmXxx(e){
    let xxxId='editInfo.xxxId';
    let xxxName='editInfo.xxxName';
    this.setData({
      [xxxId]:e.detail.value.id,
      [xxxName]:e.detail.value.text,
      disabled: false
    })
    this.onCloseXxx();
  },

  //搜索xxx
  onChangeXxxVal(e){
    this.setData({
      valueSearchXxx: e.detail
    })
    this.getXxxList();
  },

  //清除xxx选择
  onCancelXxx(){
    let xxxId='editInfo.xxxId';
    let xxxName='editInfo.xxxName';
    this.setData({
      [xxxId]:null,
      [xxxName]:''
    })
    this.onCloseXxx();
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    if(imgUrls.length){
      let pic='editInfo.pic';
      this.setData({
        [pic]: imgUrls
      })
    }


    //需要带url:的
    // let imgUrls=data.detail;
    // if(imgUrls.length){
    //   let imgArr=[];
    //   imgUrls.forEach(item => {
    //     imgArr.push({
    //       url:item
    //     });
    //   });
    //
    //   let pic='editInfo.pic';
    //   this.setData({
    //     [pic]: imgArr
    //   })
    // }
  },

  //单选  值为字符串，提交时注意判断
  onChangeDutyPerson(event) {
    let dutyPerson='editInfo.dutyPerson';
    this.setData({
      [dutyPerson]: event.detail
    })
  },
//返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },


  //查询字典
  getDictionary(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'xxx',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            id:item.id,
            text:item.name
          });
        });
        this.setData({
          xxxList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //显示开始时间
  onShowStartTime(){
    this.setData({
			showStartTime: true
    })
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    let startTime='editInfo.startTime';
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      [startTime]:util.timeFormat(e.detail),
    })
    this.onCloseStartTime();
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
			showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    let endTime='editInfo.endTime';
    this.setData({
      currentEnd: e.detail,
      maxDate1:e.detail,
      [endTime]:util.timeFormat(e.detail),
    })
    this.onCloseEndTime();
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //xxx
    if(field=='server'){
      this.setData({
        selectTitle: 'xxx',
        showSelectSearch: false
      })
      this.getServerList();
    }

    //循环-xxx
    if(field=='name2'){
        this.setData({
          selectTitle: 'xxx',
          showSelectSearch: true,
          currentIndex: dataset.index,
          currentLoop: dataset.current
        })
        this.getServerList();
      }



  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //xxx
    if(selectField=='server'){
      obj='editInfo.server';
    }

    //循环-xxx
    if(selectField=='name2'){
        let obj=e.detail.value.obj;
        let currentIndex=this.data.currentIndex;
        let list=this.data.loopList;

        list.forEach((item,index) => {
          if(index==currentIndex){
            item.name2=obj;
          }
        });

        this.setData({
          loopList: list,
          disabled: false
        })
      }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //xxx
    if(selectField=='server'){
      obj='editInfo.server';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //xxx
    if(selectField=='staff'){
      this.getXxxxxList();
    }
  },

  //查询xxx
  getXxxxList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'server',
        selectFields: ['id','name']
      }
    }

    if(this.data.valueSearch){
      param.data.xxx='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },









  //添加循环表单
  onAddLoop(){
    let list=this.data.loopList;

    //未填写不能加新的
    if(list.length){
        let len=list.length-1;
        if(list[len].name1){
        }else{
            Toast.fail('当前xx信息未完成');
            return;
        }
    }

    list.push({
        name1: null,
        name2: null,
        num: 1
    });

    this.setData({
        loopList: list,
        disabled: false
    })
  },

  //删除循环表单
  ondeleteLoop(e){
    Dialog.confirm({
      title: '确认删除xxx吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {
      let list=this.data.loopList;
      let dataset=e.currentTarget.dataset;
      let arr=[];

      list.forEach((item,index) => {
        if(index!=dataset.index){
          arr.push(item);
        }
      });

      this.setData({
        loopList: arr
      })
    }).catch(() => {
    });


    Dialog.confirm({
      title: '确认删除xxx吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {

    }).catch(() => {
    });


  },



  //获取数量
  onChangeNum(e) {
    let list=this.data.loopList;
    let dataset=e.currentTarget.dataset;

    list.forEach((item,index) => {
      if(index==dataset.index){
        item.num=e.detail;
      }
    });

    this.setData({
      loopList: list,
      disabled: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})
